from django import forms
from django.contrib.auth import get_user_model
from .models import *
from app.models import *
User = get_user_model()

class RegisterForm(forms.Form):
    username = forms.CharField(max_length=20, min_length=6, error_messages={
        'required': '用户名不能为空',
        'max_length': '用户名长度不能超过20',
        'min_length': '用户名长度不能小于6',
    })
    email = forms.EmailField(error_messages={
        'required': '邮箱不能为空',
        'invalid': '邮箱格式不正确',
    })
    password = forms.CharField(max_length=20, min_length=6, error_messages={
        'required': '密码不能为空',
        'max_length': '密码长度不能超过20',
        'min_length': '密码长度不能小于6',
    })
    captcha = forms.CharField(max_length=6, min_length=6, error_messages={
        'required': '验证码不能为空',
        'max_length': '验证码长度不能超过6',
        'min_length': '验证码长度不能小于6',
    })

    # 校验邮箱是否已存在
    def clean_email(self):
        email = self.cleaned_data.get('email')
        exists = User.objects.filter(email=email).exists()
        if exists:
            raise forms.ValidationError('邮箱已存在')
        else:
            return email
    # 验证验证码
    def clean_captcha(self):
        captcha = self.cleaned_data.get('captcha')
        email = self.cleaned_data.get('email')
        captcha_model = CaptchaModel.objects.filter(email=email, captcha=str(captcha)).first()
        if not captcha_model:
            raise forms.ValidationError('验证码错误')
        else:
            captcha_model.delete()
            return captcha



class LoginForm(forms.Form):
    email = forms.EmailField(error_messages={
        'required': '邮箱不能为空',
        'invalid': '邮箱格式不正确',
    })
    password = forms.CharField(max_length=20, min_length=6, error_messages={
        'required': '密码不能为空',
        'max_length': '密码长度不能超过20',
        'min_length': '密码长度不能小于6',
    })
    remember = forms.IntegerField(required=False)       # 指定这个字段是设置可以不传值



# 发布博客的表单
class PublishBlogForm(forms.Form):
    title = forms.CharField(max_length=200, error_messages={
        'required': '标题不能为空',
        'max_length': '标题长度不能超过200',
    })
    content = forms.CharField(error_messages={
        'required': '内容不能为空',
    })
    category = forms.ModelChoiceField(queryset=BlogCategoryModel.objects.all(), error_messages={
        'required': '分类不能为空',
    })